import Cookies from "js-cookie";
import { useUserStoreHook } from "@/store/modules/user";
import { storageLocal, isString, isIncludeAllChildren } from "@pureadmin/utils";

export const adminKey = "admin-info";
export const TokenKey = "authorized-token";
/**
 * 通过`multiple-tabs`是否在`cookie`中，判断用户是否已经登录系统，
 * 从而支持多标签页打开已经登录的系统后无需再登录。
 * 浏览器完全关闭后`multiple-tabs`将自动从`cookie`中销毁，
 * 再次打开浏览器需要重新登录系统
 * */
export const multipleTabsKey = "multiple-tabs";

/** 获取`token` */
/** 获取`token` */
export function getToken(): string {
  return useUserStoreHook().token;
}

export function useStorage() {
  return {
    saveAdmin: (admin: AdminView) => {
      localStorage.setItem(adminKey, JSON.stringify(admin));
    },
    saveToken: (token: string) => {
      localStorage.setItem(TokenKey, token);
    },
    getAdmin: (): AdminView => {
      let json = localStorage.getItem(adminKey) ?? "";
      if (json) return JSON.parse(json);
      else return {} as AdminView;
    },
    getToken: (): string => {
      return localStorage.getItem(TokenKey) ?? "";
    },
    clear: () => {
      localStorage.removeItem(adminKey);
      localStorage.removeItem(TokenKey);
    }
  };
}

/** 删除`token`以及key值为`user-info`的localStorage信息 */
export function removeToken() {
  useStorage().clear();
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return "Bearer " + token;
};

/** 是否有按钮级别的权限（根据登录接口返回的`permissions`字段进行判断）*/
export const hasPerms = (value: string | Array<string>): boolean => {
  if (!value) return false;
  const allPerms = "*:*:*";
  //此处是用户的权限，暂时为空
  const permissions = [];
  if (!permissions) return false;
  if (permissions.length === 1 && permissions[0] === allPerms) return true;
  const isAuths = isString(value)
    ? permissions.includes(value)
    : isIncludeAllChildren(value, permissions);
  return isAuths ? true : false;
};
